import {
    LockOutlined,
    UserOutlined,
} from '@ant-design/icons';
import { Alert, message, Typography, Row, Col, Divider } from 'antd';
import React, { useState, FC } from 'react';
import { ProFormText, LoginForm } from '@ant-design/pro-form';
import { history, Link, useModel, ConnectProps, IndexModelState } from 'umi';

import $utils from '@/utils/utils';
import { login } from '@/services/user';

import styles from './index.less';

import logoP from '../../../../public/logo.png';


interface PageProps extends ConnectProps {
    index: IndexModelState;
    loading: boolean;
}

const LoginMessage: React.FC<{
    content: string;
}> = ({ content }) => (
    <Alert
        style={{
            marginBottom: 24,
        }}
        message={content}
        type="error"
        showIcon
    />
);

const { Title } = Typography;

const Login: FC<PageProps> = ({ dispatch, index }) => {
    const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
    const { initialState, setInitialState } = useModel('@@initialState');

    const setUserInfo = async (userInfo: API.CurrentUser) => {
        if (userInfo) {
            setTimeout(() => {
                initialState?.setRegionList?.(userInfo);
            }, 0)
            await setInitialState((s) => ({
                ...s,
                currentUser: userInfo,
            }));
        }
    };

    const handleSubmit = async (values: any) => {
        try {
            // 登录
            const msg = await login({ phone: values.phone, password: values.password });
            if (msg.code === 0) {

                $utils.setStorage('user_info', msg.body, 2 * 3600 * 1000);
                await setUserInfo(msg.body);


                /** 此方法会跳转到 redirect 参数所在的位置 */
                if (!history) return;
                if (msg.body.status === 0) {
                    message.success('首次登录，初始化密码');
                    history.push({
                        pathname: '/user/pwd',
                        state: 'init'
                    });
                    return;
                }

                const { query } = history.location;
                message.success('登录成功！');
                const { redirect } = query as { redirect: string };
                history.push(redirect || '/');
                return;
            }
            // 如果失败去设置用户错误信息
            setUserLoginState(msg);
        } catch (error) {
            console.log(error);
            message.error('登录失败，请重试！');
        }
    };
    const { status, type: loginType } = userLoginState;

    return (
        <div className={styles.container}>
            {/* <div className={styles.header}>
                <Row className={styles.Rows} style={{ width: '100%', height: '80px', lineHeight: '80px', paddingLeft: '10%' }}>
                    <Col span={8}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <img style={{ width: '28px' }} src={logoP} />
                            <span style={{ fontSize: '18px', marginLeft: '6px' }}>晨星运营管理系统</span>
                        </div>
                    </Col>
                    <Col span={12}>
                        <div style={{ fontSize: '28px', marginLeft: '6px' }}>
                            顺畅物流+便利生活
                        </div>
                    </Col>
                </Row>
            </div> */}
            <div className={styles.content}>
                <div style={{ fontSize: '60px', color: '#fff', marginTop: '4%', marginBottom: '60px' }}>
                    顺畅物流+便利生活
                </div>
                <Row className={styles.Rows} style={{ backgroundColor: '#fff', padding: '40px', maxWidth: '850px' }}>
                    <Col span={12} style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                        <div className={styles.leftLogo}></div>
                        <div className={styles.companyName}>中科富创</div>
                    </Col>
                    <Col span={11}>
                        <div style={{ display: 'flex', height: '100%' }}>
                            <Divider className={styles.Dividers} type="vertical" />
                            <div style={{ display: 'flex', flexDirection: 'column', }}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                    <img style={{ width: '56px' }} src={logoP} />
                                    <span style={{ fontSize: '30px', color: '333', marginLeft: '6px' }}>晨星运营管理系统</span>
                                </div>
                                <LoginForm
                                    initialValues={{
                                        autoLogin: true,
                                    }}
                                    onFinish={async (values) => {
                                        await handleSubmit(values);
                                    }}
                                >
                                    {status === 'error' && loginType === 'account' && (
                                        <LoginMessage
                                            content={'账户或密码错误'}
                                        />
                                    )}
                                    <>
                                        <ProFormText
                                            name="phone"
                                            fieldProps={{
                                                size: 'large',
                                                prefix: <UserOutlined className={styles.prefixIcon} />,
                                                maxLength: 11
                                            }}
                                            placeholder={'请输入手机号码'}
                                            rules={[
                                                {
                                                    required: true,
                                                },
                                            ]}
                                        />
                                        <ProFormText.Password
                                            name="password"
                                            fieldProps={{
                                                size: 'large',
                                                prefix: <LockOutlined className={styles.prefixIcon} />,
                                                maxLength: 20
                                            }}
                                            placeholder={'请输入密码'}
                                            rules={[
                                                {
                                                    required: true,
                                                },
                                            ]}
                                        />
                                    </>
                                </LoginForm>
                                <div
                                    style={{
                                        marginBottom: 24,
                                        textAlign: 'right',
                                    }}
                                >
                                    <Link to="/user/pwd">
                                        找回密码
                                    </Link>
                                </div></div>
                        </div>
                    </Col>
                </Row>
            </div>
        </div >
    );
};

export default Login;
